package com.an.blog.third.job;

import com.an.blog.admin.domain.vo.BlogDailyImageVo;
import com.an.blog.service.IBlogDailyImageService;
import com.an.blog.utils.ConvertUtil;
import com.an.common.constant.CacheConstants;
import com.an.common.constant.SysConfigConstants;
import com.an.common.utils.redis.RedisUtils;
import com.an.system.domain.vo.SysOssVo;
import com.an.system.service.ISysConfigService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 博客定时任务服务
 *
 * @author: Ann
 * @createDate: 2023/09/25 11:14:37
 * @version: 1.0.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BlogJobService {

    private final IBlogDailyImageService dailyImageService;

    private final ISysConfigService sysConfigService;


    /**
     * 刷新图像缓存处理程序
     *
     * @return {@link List }<{@link BlogDailyImageVo }>
     * @author: Ann
     * @createDate: 2023/09/25 14:14:21
     * @version: 1.0.0
     */
    @XxlJob("refreshImageCacheHandler")
    public List<BlogDailyImageVo> refreshImageCacheHandler() {
        //选择参数配置中的默认轮播图数量
        String defaultNumber = sysConfigService.selectConfigByKey(SysConfigConstants.BLOG_DAILY_IMAGE_NUMBER);
        //随机查询固定数量的图片信息
        List<BlogDailyImageVo> blogDailyImageVoList =  dailyImageService.queryListByRandom(defaultNumber);
        Map<Long, SysOssVo> sysOssVoMap = ConvertUtil.convert2OssIdSysOssMap(blogDailyImageVoList, BlogDailyImageVo::getImage);
        blogDailyImageVoList.forEach(blogDailyImageVo -> {
            SysOssVo sysOssVo = sysOssVoMap.get(blogDailyImageVo.getImage());
            blogDailyImageVo.setImageUrl(sysOssVo != null ? sysOssVo.getUrl() : null);
        });
        //插入到redis,门户网站查询使用
        boolean existsObject = RedisUtils.isExistsObject(CacheConstants.BLOG_DAILY_IMAGE);
        if (existsObject) {
            RedisUtils.deleteObject(CacheConstants.BLOG_DAILY_IMAGE);
        }
        RedisUtils.setCacheList(CacheConstants.BLOG_DAILY_IMAGE,blogDailyImageVoList);
        log.info("执行每日轮播图更新任务完成");
        return blogDailyImageVoList;
    }

}
